#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext import webapp

from StringIO import StringIO
from GPXtoKML import GPXtoKML
from GPXTimeline import GPXTimeline
from Picasa import Picasa
from xml.etree.ElementTree import Element, SubElement, ElementTree, fromstring

#
# Return a KML data file.
#


def buildKML( out_f, photos, name="Photo album" ):
  kml = Element( 'kml' )
  kml.attrib['creator'] = 'PhotoLocate'
  kml.attrib['xmlns'] = 'http://earth.google.com/kml/2.2'
  folder = SubElement( kml, 'Folder' )
  name = SubElement( folder, 'name' )
  name.text = name
  for pic in photos:
    place = SubElement( folder, 'Placemark' )
    style = SubElement( place, 'Style' )
    istyle = SubElement( style, 'IconStyle' )
    #scale = SubElement( istyle, 'scale' )
    #scale.text = "2.0"
    icon = SubElement( istyle, 'Icon' )
    href = SubElement( icon, 'href' )
    href.text = pic.icon
    name = SubElement( place, 'name' )
    name.text = pic.title
    desc = SubElement( place, 'description' )
    desc.text = """
<div style="width:360px;height:295px" class="info-window">
<a href="%s"><img src="%s" /></a>
</div>""" % (pic.webpage, pic.thumbnail)

    time_str = pic.getDatetime().strftime("%Y%m%d%H%M%S")
    point =  SubElement( place, 'Point' )
    point.attrib['id'] = time_str
    coords = SubElement( point, 'coordinates' )
    coords.text = "%f,%f" % (pic.lon, pic.lat)
    #netlink = SubElement( folder, 'NetworkLink' )
    #name = SubElement( netlink, 'name' )
    #name.text = "%s locate" % (pic.title)
    #link = SubElement(netlink, 'Link' )
    #href = SubElement(link, 'href' )
    #href.text = "%stime=%s" %(base_url,time_str)
    pass
  out_f.write( '<?xml version="1.0" encoding="UTF-8"?>\n' )
  ElementTree( kml ).write( out_f )
  return



class AlbumKML(webapp.RequestHandler):
  def get(self):
    track_key = self.request.get('key')
    is_netlink_request = self.request.get('net')
    track = db.get(db.Key(track_key))
    track_url = "%s/download?key=%s" % (self.request.host_url, track_key)

    if self.request.path == "/kmllink":
      urlres = urlfetch.fetch(track.album)
      if urlres.status_code != 200:
        return
      self.response.headers['Content-Type']='application/vnd.google-earth.kml+xml'
      self.response.headers['Content-Disposition']='attachment;filename=%s.kml' % track.albumName.encode('ascii')
      base_url = "%s/locate?key=%s&" % (self.request.host_url, track_key)
      photos = Picasa(urlres.content).photos()
      GPXTimeline(track.getContent()).getPhotoLocations(photos, track.timeSlip)
      buildKML(self.response.out, photos, track.albumName)
    else:
      self.response.headers['Content-Type']='application/vnd.google-earth.kml+xml'
      self.response.headers['Content-Disposition']='attachment;filename=%s.kml' % track.name.encode('ascii')
      netlink_url = "%s/kmllink?key=%s" % (self.request.host_url,track_key)
      self.response.out.write("""<?xml version="1.0" encoding="UTF-8"?>
      <kml xmlns="http://earth.google.com/kml/2.2">
      <Folder>
      <NetworkLink><name>%s</name><Link><href>%s</href></Link></NetworkLink>
      <NetworkLink><name>%s</name><Link><href>%s</href></Link></NetworkLink>
      </Folder>
      </kml>""" % (track.albumName, netlink_url, track.name, track_url))

      return

